/*
  Learn ES5 module.exports.
  When cloud database is unavailable, used the mock data.
  */
const mockArticleList = require('../../mockData/mockArticles');
//Imporrt the Vant Weapp 3rd components.
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
//Import each part of home page service.
import {dimension2ArticleListService} from '../../service/homePage/dimension2ArticleList/dimension2ArticleListService';
import {categoryService} from '../../service/homePage/category/categoryService';
import {specialMomentService} from '../../service/homePage/specialMoment/specialMomentService';

//Import utils for some common data handle.
import {utils} from '../../utils/utils';

//Add the flag to control the data retrieval from database.
const loadFromCloudBase = true

//Define the Dimension filter conditions.
const selectedDimensionList = ['createdTime', 'viewTimes', 'modifyTimes', 'contentAmount'];

//Define the special moment ICON
const specMomentICONArray = ['--meet', '--belief', '--beloved', '--miss']

Page({

  /**
   * 页面的初始数据
   */
  data: {
    specMomentList : [],
    specMomentListSize : 0,
    defaultSpecMomentList : [1, 2, 3, 4],
    categoryList : [],
    categoryListSize : 0,
    defaultCategoryList : ['日记', '古代汉语', '现代汉语', '新闻', '论文', '语录', '忏悔', '计划书'],
    refactorArticleList : [],
    selectedDimensionID : 0,
    picIndexRandomArray : [],
  },

  /*
   Resolve each of the retrival data from specified service
  */
 retrieveEachServiceData() {
  let articleList = dimension2ArticleListService.aggregatedArticleList(this, mockArticleList, loadFromCloudBase);
  console.log(`Retrieve the articleList from 'dimension2ArticleListService.aggregatedArticleList' : ${articleList}`);

  let categoryList = categoryService.aggregatedCategory();
  console.log(`Retrieve the category list from 'categoryService.aggregatedCategory' : ${categoryList}`);
  
  let specMomentList = specialMomentService.aggregatedSpecialMoment();
  console.log(`Retrieve the specMomentList list from 'specialMomentService.aggregatedSpecialMoment' : ${specMomentList}`);

  //TODO : Consider to use RXJS instead of Promise in the future.
  return Promise.all([articleList, categoryList, specMomentList])
        .then(res => {
          let refactorArticleList = res[0];
          
          categoryList = categoryList ? res[1] : this.defaultCategoryList;
          let categoryListSize = categoryList.length;
        
          specMomentList = specMomentList ? res[2] : this.defaultSpecMomentList;
          let specMomentListSize = specMomentList.length;
           //Handle the special moment icon
           specMomentList.forEach((specMoment, index)=> {
            specMoment['IconID'] = specMomentICONArray[index];
          });

          console.log(`Succeed to retrieve the aggregated data from : ${dimension2ArticleListService.articleListWithCondQueryRequest.originCollection}, ${categoryService.categoryQueryRequest.originCollection}, ${specialMomentService.specialMomentQueryRequest.originCollection}, ready to resolve the promises from Promise.all => refactorArticleList ========= ${refactorArticleList}, categoryList ============ ${categoryList}, specMomentList =========== ${specMomentList}`);
          
          this.setData({
            refactorArticleList,
            categoryList,
            categoryListSize,
            specMomentList,
            specMomentListSize
          });
        });
  },

  /* Define selection event */
  selectDimension(event) {
    let selectedDimensionID = event.target.id * 1
    let orderBy = selectedDimensionList[selectedDimensionID];
    console.log(`Ready to retrieve the aggregated article list orderBy ============= ${orderBy}`);
    let articleListWithCondQueryRequest = dimension2ArticleListService.articleListWithCondQueryRequest;
    articleListWithCondQueryRequest.orderBy = orderBy;

    wx.cloud.callFunction({
      name : "AggregatedLookUpForDimension2ArticleList",
      data : {
        queryRequest : articleListWithCondQueryRequest
      }
    })
    .then(res => {
      let articleList = res.result;
      console.log(`Succeed to retrieve articleList : ${articleList} by specified dimention : ${orderBy}`);

      let refactorArticleList = dimension2ArticleListService.resolveAggregatedArticleList(articleList, this)
      console.log(`After resolve the aggregated article list, refactorArticleList : ${refactorArticleList}`);

      this.setData({
        refactorArticleList,
        selectedDimensionID
      });
    });
  },

  /*Define navigation */
  navigateToTargetArticleListPage(event) {
    let specMomentID = event.target.dataset.specmomentid;

    if(!specMomentID) {
      console.log(`Current ${event.target.dataset.name} Special Moment contains no articles...`);
      return;
    };

    wx.navigateTo({
      url : "../articleList/articleList",
      events : {

      },
      success : function(res) {
        res.eventChannel.emit('receiveSpecialMomentID', {specMomentID});
      }
    });
  },

  navigateToTargetArticleDetailsPage(event) {
    let dataset = event.target.dataset;
    let articleID = dataset.articleid;
    let createdTime = dataset.createdtime;

    wx.navigateTo({
      url : "../articleDetails/articleDetails",
      events : {

      },
      success : function(res) {
        res.eventChannel.emit('receiveArticleID', {articleID, createdTime});
      }
    });
  },
  /* End to define navigation */

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.retrieveEachServiceData()
    .then(res => {
      console.log("Finish all the services data retrieval...");
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // utils.mockUpArticlePic(this);
    Toast('下拉刷新数据喔~');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log("触发下拉刷新事件，开始加载数据...");
    this.retrieveEachServiceData()
    .then(res => {
      console.log("Finish all the services data retrieval...");
      wx.stopPullDownRefresh({
        success: (res) => {
          console.log("已完成下拉刷新...");
        },
      });
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})